package org.chunyan.exam.service.examcomputer;

import cn.hutool.core.lang.Singleton;
import org.chunyan.exam.entity.MyApplication;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExamComputerServiceImpl implements ExamComputerService{
    private final static String APP_NAME = "XIANGXIANG";
    @Override
    public boolean isStartupEnabled() {
        try {
            // 构造查询命令
            String query = "reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\" /v " + APP_NAME;
            Process process = Runtime.getRuntime().exec(query);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            // 读取命令的输出
            while ((line = reader.readLine()) != null) {
                if (line.contains(APP_NAME)) {
                    return true; // 如果找到了对应的键，表示已设置开机自启
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false; // 默认返回false
    }

    @Override
    public boolean enableComputerStartup(String path) {
        boolean result = false;
        try {
            Runtime.getRuntime().exec(new String[]{
                    "reg",
                    "add",
                    "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
                    "/v",
                    APP_NAME,
                    "/t",
                    "REG_SZ",
                    "/d",
                    "\"" + path + "\"", // 使用程序获取的路径，并确保路径被双引号包围，以支持路径中的空格
                    "/f"
            });
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean disableComputerStartup() {
        boolean result = false;
        try {
            Runtime.getRuntime().exec(new String[]{
                    "reg",
                    "delete",
                    "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
                    "/v",
                    APP_NAME,
                    "/f"
            });
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public String getApplicationPath() {
        MyApplication application = Singleton.get(MyApplication.class);
        return application.getRunPath();
    }
}
